<template>
    <div class="container">
        <!-- 顶部统计 -->
        <el-row>
            <div class="card" style="width: 100%; height: 100px">
                <div id="d1" ref="c3Ref" style="width: 100%; height: 150px"></div>
            </div>
        </el-row>

        <!-- 待处理事务 -->
        <el-row>
            <el-col :span="12">
                <div class="card" style="height: 400px">
                    <h3 style="text-align: center;">数据统计</h3>
                    <el-row>
                        <el-col :span="8">
                            <div class="card">
                                <h3 style="text-align: center;">订单总数</h3>
                                <div class="count">
                                    {{ countOrders }}单

                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="card">
                                <h3 style="text-align: center;">销售总额</h3>
                                <div class="count">
                                    {{ countPrices }}
                                    <span>元</span>
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="card">
                                <h3 style="text-align: center;">用户总数</h3>
                                <div class="count">{{ countMembers }}个</div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
            <el-col :span="12">
                <!--饼状图-->
                <div class="card">
                    <div class="charts" ref="c2Ref" style=" height: 400px;"></div>
                </div>
            </el-col>
        </el-row>


        <!-- 订单统计 -->
        <el-row>
            <el-col :span="24">
                <div class="card">
                    <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
                        @change="handleDateRangeChange" style="margin-bottom: 20px;" />
                    <h3 style="text-align: center;font-size: 30px;">订单统计</h3>
                    <div class="c4Ref" ref="c4Ref" style="width: 100%; height: 400px"></div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import * as echarts from "echarts";
import { orderCount, priceCount, hotItems, Count } from "@/api/ViewApi";
const c3Ref = ref(null);
const c4Ref = ref(null);
const c2Ref = ref(null);
const orders = ref([]);
const prices = ref([]);
const countOrders = ref(0);
const countPrices = ref(0);
const countMembers = ref(0);
const dateRange = ref([
    new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0],
    new Date().toISOString().split('T')[0]
]);
onMounted(async () => {
    await findCount();
    await nextTick();
    const chart2 = echarts.init(c2Ref.value);
    await findHotItems(chart2);
    const chart3 = echarts.init(c3Ref.value);
    chart3.setOption(c3Opts);
    const chart4 = echarts.init(c4Ref.value);
    await loadData(chart4, dateRange.value);

});

async function findCount() {
    let resp = await Count();
    countOrders.value = resp.countOrders;
    countPrices.value = resp.prices;
    countMembers.value = resp.countMembers;
}
// 加载数据并设置饼图配置项
async function findHotItems(chart2) {
    const resp = await hotItems();
    console.log(resp.data);
    c2Opts.series[0].data = resp.data;
    chart2.setOption(c2Opts);
}
const c2Opts = {
    title: {
        text: '商品销售情况',
        left: 'center'
    },
    tooltip: {
        trigger: 'item',
    },
    legend: {
        orient: 'horizontal',  // 更改为水平排列
        bottom: '5%',          // 调整图例到底部
        left: 'center',        // 居中对齐
        formatter: ''         // 设置图例名称为空
    },
    series: [
        {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            center: ['50%', '45%'],  // 调整饼图中心位置，防止与图例重叠
            data: [],
            label: {
                show: false
            },
            labelLine: {
                show: false
            },
            emphasis: {
                label: {
                    show: true
                },
                labelLine: {
                    show: true
                },
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
};
// 监听日期范围的变化
watch(dateRange, async (newDateRange) => {
    if (newDateRange[0] && newDateRange[1]) {
        const chart4 = echarts.init(c4Ref.value);
        await loadData(chart4, newDateRange);
    }
});
async function loadData(chart4, [startDate, endDate]) {
    const formatDate = (date) => {
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
    };

    const start = new Date(startDate);
    const end = new Date(endDate);

    // 生成日期范围内的日期数组
    const daysOfRange = [];
    for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
        daysOfRange.push(formatDate(new Date(d)));
    }

    orders.value = new Array(daysOfRange.length).fill(0);
    prices.value = new Array(daysOfRange.length).fill(0);
    // 从接口获取订单和价格数据
    const ordersResp = await orderCount(start, end);
    if (ordersResp && ordersResp.data) {
        ordersResp.data.forEach(item => {
            const formattedDate = formatDate(new Date(item.date));
            const index = daysOfRange.indexOf(formattedDate);
            if (index !== -1) {
                orders.value[index] = item.count;
            }
        });
    } else {
        console.warn('订单数据为空');
    }

    const pricesResp = await priceCount(start, end);
    if (pricesResp && pricesResp.data) {
        pricesResp.data.forEach(item => {
            const formattedDate = formatDate(new Date(item.date));
            const index = daysOfRange.indexOf(formattedDate);
            if (index !== -1) {
                prices.value[index] = item.count;
            }
        });
    } else {
        console.warn('价格数据为空');
    }

    // 设置图表选项
    chart4.setOption({
        ...C4Opts,
        xAxis: [
            {
                type: 'category',
                data: daysOfRange, // 使用格式化的日期显示
                axisPointer: {
                    type: 'shadow'
                },
                axisLabel: {
                    interval: 0
                }
            }
        ],
        series: [
            {
                name: '销售额',
                type: 'bar',
                yAxisIndex: 1,
                data: prices.value
            },
            {
                name: '订单数量',
                type: 'line',
                yAxisIndex: 0,
                data: orders.value
            }
        ]
    });
}

// 折线图配置项
const C4Opts = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            crossStyle: {
                color: '#999'
            }
        }
    },
    toolbox: {
        feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
        }
    },
    legend: {
        data: ['销售额', '订单数量'],
      show: false
    },
    xAxis: [
        {
            type: 'category',
            data: [], // 这里将会动态设置日期
            axisPointer: {
                type: 'shadow'
            }
        }
    ],
    yAxis: [
        {
            type: 'value',
            name: '次数',
            min: 0,
            interval: 2,
            axisLabel: {
                formatter: '{value} 次'
            }
        },
        {
            type: 'value',
            name: '金额',
            min: 0,
            interval: 5000,
            axisLabel: {
                formatter: '{value} 元'
            }
        },
    ],
    series: [
        {
            name: '销售额',
            type: 'bar',
            yAxisIndex: 1,
            tooltip: {
                valueFormatter: function (value) {
                    return value + ' 元';
                }
            },
            data: []
        },
        {
            name: '订单数量',
            type: 'line',
            tooltip: {
                valueFormatter: function (value) {
                    return value + ' 单';
                }
            },
            data: []
        }
    ]
};
// 文本动画配置项
const c3Opts = {
    graphic: {
        elements: [
            {
                type: 'text',
                left: 'center',
                top: '20',
                style: {
                    text: '商城管理系统',
                    fontSize: 70,
                    fontWeight: 'bold',
                    lineDash: [0, 200],
                    lineDashOffset: 0,
                    fill: 'transparent',
                    stroke: '#0056b3',
                    lineWidth: 1
                },
                keyframeAnimation: {
                    duration: 3000,
                    loop: false,
                    keyframes: [
                        {
                            percent: 0.7,
                            style: {
                                fill: 'transparent',
                                lineDashOffset: 200,
                                lineDash: [200, 0]
                            }
                        },
                        {
                            percent: 0.8,
                            style: {
                                fill: 'transparent'
                            }
                        },
                        {
                            percent: 1,
                            style: {
                                fill: '#0056b3',
                                stroke: '#003d7a'
                            }
                        }
                    ]
                }
            }
        ]
    }
};

</script>

<style scoped>
.container {
    min-height: 100%;
    background-color: #F5F5F5;
    padding: 20px;
}

.card {
    background-color: #FFF;
    border-radius: 5px;
    padding: 20px;
    margin-bottom: 20px;
    line-height: 10px;
}

h3 {
    color: #333;
    font-size: 18px;
    margin-bottom: 10px;
}

p {
    font-size: 24px;
    font-weight: bold;
}

.el-row {
    margin-bottom: 15px;
}

.charts {
    background-color: #fff;
    border-radius: 5px;
    padding: 0px;
}

.count {
    margin: auto;
    width: 140px;
    height: 140px;
    border: 15px solid #49BCF7;
    border-radius: 100px;
    text-align: center;
    line-height: 140px;
    font-size: 24px;
}
</style>
